<template>
  <div class="registerTabs">
    <div class="placeholder" v-if="!registerList.length">
      <div class="ph-image"></div>
      <div class="text">尚未有报读记录</div>
    </div>
    <div class="main" v-else>
      <div
        class="registerTabs-cards"
        v-for="item in registerList"
        :key="item.registerList"
      >
        <div class="btn" style="float: right">
          <el-button
            @click="toClassEnding(item.courseId)"
            :disabled="item.exhaustedButton == 0"
            v-hasPermi="['student:course:option']"
            >结课</el-button
          >

          <el-button
            @click="toStopLesson(item.courseId)"
            :disabled="item.stopsResume === 0"
            v-hasPermi="['student:course:option']"
            >{{ item.stopsResume === 0 ? "已停课" : "停课" }}</el-button
          >
          <el-button
            v-hasPermi="['student:course:option']"
            @click="toResumeLesson(item.courseId)"
            :disabled="item.stopsResume === 1"
            >复课</el-button
          >
        </div>
        <div style="font-weight: bold; margin-bottom: 5px">
          {{ item.courseName }}
        </div>
        <el-row style="margin-bottom: 15px">
          <el-col :span="8">
            <p class="item">
              <span class="props">剩余课时: </span
              >{{
                item.remainderLesson > 0 ? Math.abs(item.remainderLesson) : "0"
              }}课时
            </p>

            <!-- <p class="item">
              <span class="props">所在班级: </span>{{ item.addTime }}
            </p> -->
          </el-col>
          <el-col :span="8">
            <p class="item">
              <span class="props">消耗课时: </span
              >{{ item.countLessonComplete }}课时
            </p>
          </el-col>
          <el-col :span="8">
            <p class="item">
              <span class="props">合计购买课时: </span
              >{{ item.countLessonTotal }}课时
            </p>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 15px">
          <el-col :span="16" style="display: flex; align-items: center">
            <span style="margin-right: 5px">所在班级: </span>
            <div class="item" v-if="!item.ifedit">
              <span style="color: rgb(121.3, 187.1, 255)">{{
                item.classNames ? item.classNames : "暂未加入任何班级"
              }}</span>
              <div class="edit-icon-style" @click="item.ifedit = true">
                <EditPen style="width: 1em; height: 1em; margin-right: 8px" />
              </div>
            </div>
            <div v-else style="display: flex">
              <el-select
                v-model="item.classIdArr"
                placeholder="请选择所在班级"
                style="min-width: 150px"
                multiple
                clearable
              >
                <el-option
                  v-for="value in item.studentClassDtos"
                  :key="value.id"
                  :label="value.name"
                  :value="value.id"
                />
              </el-select>
              <div class="check-icon-style" @click="toAddStudentToClass(item)">
                <Check style="width: 1em; height: 1em; margin-right: 8px" />
              </div>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTableRef"
          :data="item.tstudentCourseDtos"
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column
            label="订单号"
            fixed="left"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              <router-link
                :to="'/financial/orderManage/details/' + scope.row.id"
                class="link-type"
              >
                <span style="color: #67c23a; cursor: pointer">{{
                  scope.row.orderNo
                }}</span>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column
            label="购买数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.countLessonTotalNormal }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="赠送数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{
                scope.row.countLessonTotalGive
                  ? `${scope.row.countLessonTotalGive}课时`
                  : "-"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="已消耗数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{
                scope.row.countLessonComplete
                  ? `${scope.row.countLessonComplete}课时`
                  : "-"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="退转数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{
                scope.row.countLessonRefund
                  ? `${scope.row.countLessonRefund}课时`
                  : "-"
              }}
            </template>
          </el-table-column>
          <el-table-column
            label="剩余数量"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{
                scope.row.remainderLesson > 0
                  ? Math.abs(scope.row.remainderLesson)
                  : "0"
              }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="超上课时"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.exceed > 0 ? Math.abs(scope.row.exceed) : "0" }}课时
            </template>
          </el-table-column>
          <el-table-column
            label="到期日期"
            :header-cell-style="headerCellStyle"
            :formatter="formatName"
            width="240"
          >
            <template #header>
              <span style="margin-right: 8px">到期日期</span>
              <el-tooltip
                class="item"
                effect="dark"
                content="该时间是创建订单时所设置的课程有效期时间"
                placement="top"
              >
                <el-icon color="#C0C4CC" size="16px"
                  ><QuestionFilled
                /></el-icon>
              </el-tooltip>
            </template>
            <template #default="scope">
              <!-- {{ scope.row.expireDate ? scope.row.expireDate : '长期有效' }} -->
              <el-date-picker
                v-model="scope.row.expireDate"
                style="width: 80%"
                type="date"
                placeholder="请选择日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                @change="toChangeExpireDate(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="课程状态"
            show-overflow-tooltip
            :formatter="formatName"
          >
            <template #default="scope">
              {{ scope.row.exhausted === "1" ? "未结课" : "已结课" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                :disabled="scope.row.exhausted !== '1'"
                link
                type="primary"
                @click="handleSignUp(scope.row)"
                v-hasPermi="['student:course:option']"
              >
                课时清零
              </el-button>
              <el-button
                :disabled="scope.row.exhausted !== '1'"
                link
                type="primary"
                @click="toDealExceed(scope.row)"
                v-hasPermi="['student:course:option']"
              >
                处理超上
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
  getIstSecond,
  updateLesson,
  dealExceed,
  classEndingApi,
  stopsAndResumeApi,
  addStudentToClass,
} from "@/api/studentManagement/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
const props = defineProps({
  studentId: {
    type: String,
  },
});
const emit = defineEmits(["update:unClassList"]);
//获取报读情况列表
const loading = ref(false);
const registerList = reactive([]);
const toGetIstSecond = async () => {
  loading.value = true;
  try {
    const res = await getIstSecond({ studentId: props.studentId });
    if (res.code == 200) {
      loading.value = false;
      registerList.splice(0, registerList.length);
      registerList.push(...(res.data || []));
      const unClassList = res.data.flatMap((item) =>
        item.tstudentCourseDtos.filter((val) => val.exhausted === "1")
      );
      emit("update:unClassList", unClassList);
    }
  } catch (error) {
    console.error("获取报读情况列表失败:", error);
  }
};
onMounted(toGetIstSecond);
//课时清零
const handleSignUp = (row) => {
  ElMessageBox.confirm("是否确定课时清零", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        exhausted: 0,
        id: row.id,
      };
      try {
        const res = await updateLesson(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "操作成功",
          });
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消清零",
      });
    });
};
//结课
const toClassEnding = (row) => {
  ElMessageBox.confirm("是否确定结课", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        studentId: props.studentId,
        courseId: row,
      };
      try {
        const res = await classEndingApi(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "操作成功",
          });
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消结课",
      });
    });
};
//停课
const toStopLesson = (row) => {
  ElMessageBox.confirm(
    "停课后，该报读课程将会从班级排课中移除,是否确定停课?",
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      const params = {
        studentId: props.studentId,
        courseId: row,
        stopsResume: 0,
      };
      try {
        const res = await stopsAndResumeApi(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "操作成功",
          });
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消停课",
      });
    });
};
//复课
const toResumeLesson = (row) => {
  ElMessageBox.confirm("复课后，需重新排课,是否确定复课?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        studentId: props.studentId,
        courseId: row,
        stopsResume: 1,
      };
      try {
        const res = await stopsAndResumeApi(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "操作成功",
          });
        }
      } catch (error) {
        console.error("操作失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消复课",
      });
    });
};
//选择到期日期
const toChangeExpireDate = async (row) => {
  const params = {
    expireDate: row.expireDate,
    id: row.id,
  };
  try {
    const res = await updateLesson(params);
    if (res.code == 200) {
      ElMessage({
        type: "success",
        message: "修改成功",
      });
    }
  } catch (error) {
    console.error("获取报读情况列表失败:", error);
  }
};
//超上处理
const toDealExceed = (row) => {
  ElMessageBox.confirm("是否确定处理超上", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = {
        id: row.id,
      };
      try {
        const res = await dealExceed(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "处理成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      } catch (error) {
        console.error("处理失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消处理",
      });
    });
};
defineExpose({ toGetIstSecond }); // 用于父组件调用

//分配班级
const toAddStudentToClass = (row) => {
  row.ifedit = false;
  ElMessageBox.confirm("是否确定分配班级", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const params = row.classIdArr.length
        ? row.classIdArr.map((classId) => ({
            studentId: props.studentId,
            consumeCourseId: row.courseId,
            classId,
          }))
        : [
            {
              studentId: props.studentId,
              consumeCourseId: row.courseId,
              classId: null,
            },
          ];

      console.log(params);
      try {
        const res = await addStudentToClass(params);
        if (res.code == 200) {
          toGetIstSecond();
          ElMessage({
            type: "success",
            message: "分配成功",
          });
        } else {
          ElMessage({
            type: "error",
            message: res.msg,
          });
        }
      } catch (error) {
        console.error("处理失败:", error);
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消分配",
      });
    });
};
</script>

<style lang="scss" scoped>
.registerTabs {
  .placeholder {
    height: 200px;
    .ph-image {
      width: 240px;
      height: 110px;
      margin: 0 auto;
      background-image: url("@/assets/images/phImage.png"); /* 设置背景图片 */
      background-size: cover; /* 背景图片覆盖整个容器 */
      background-position: center; /* 背景图片居中显示 */
      background-repeat: no-repeat; /* 背景图片不重复 */
    }
    .text {
      text-align: center;
      color: #333;
      font-size: 16px;
    }
  }
  .main {
    .registerTabs-cards {
      margin-bottom: 20px;
      border: 1px solid rgb(232.8, 233.4, 234.6);
      padding: 20px;
      .edit-icon-style {
        display: inline-block;
        font-size: 20px;
        text-align: right;
        cursor: pointer;
        margin-left: 20px;
      }
      .check-icon-style {
        font-size: 20px;
        height: 32px;
        display: flex;
        align-items: center;
        margin-left: 10px;
        cursor: pointer;
      }
      .item {
        display: flex;
        color: #000;
        align-items: center;
        margin: 5px 0;
        .props {
          // width: 40px;
          margin-right: 5px;
          color: #333;
        }
      }
    }
  }
}
</style>
